//
//  CountDown.swift
//  Casecord
//
//  Created by baozi on 2024/1/4.
//

import Foundation
import RxSwift

class CountDown {
    static func timer(count: Int, interval: RxTimeInterval = .seconds(1)) -> Observable<(isStop: Bool, leftTime: CGFloat)> {
        return Observable<(isStop: Bool, leftTime: CGFloat)>.create { obs in
            let timer = Observable<Int>
                .interval(
                    interval,
                    scheduler: MainScheduler.asyncInstance
                )
                .map { v in
                    switch interval {
                    case let .seconds(step):
                        return CGFloat(count) - CGFloat(v * step)
                    case let .milliseconds(step):
                        return CGFloat(count) - (CGFloat(v * step) / 1000)
                    default:
                        PPLog("不接受别的类型")
                        return 0
                    }
                }
                .subscribe(onNext: { value in
//                    PPLog("\(value)")
                    if value > 0 {
                        obs.onNext((false, value))
                    } else {
                        obs.onNext((true, 0))
                        obs.onCompleted()
                    }
                }, onDisposed: {
                    PPLog("我也销毁了")
                })
            return Disposables.create {
                timer.dispose()
            }
        }
    }
}
